package leetcode.D100.T92;

import util.ListNode;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: DYZ
 * @Create: 2022-02-18 15:50:50
 */
class Solution {

    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(0, head), prev = dummy;
        for(int i=0; i<left-1; ++i) {
            prev = prev.next;
        }
        prev.next = reverseK(prev.next, right - left + 1);
        return dummy.next;
    }

    private ListNode reverseK(ListNode head, int k) {
        if (k == 1) {
            return head;
        }
        ListNode tempHead = reverseK(head.next, k - 1);
        ListNode tail = head.next;
        head.next = tail.next;
        tail.next = head;
        return tempHead;
    }
}
